package com.shenyue.nbtownlet.adapter;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shenyue.nbtownlet.R;
import com.shenyue.nbtownlet.databinding.ProjectFundListItemBinding;
import com.shenyue.nbtownlet.util.StringUtil;

public class ProjectFundListViewAdapter extends BaseAdapter {
    private Context mContext;
    private JSONArray items = new JSONArray();

    public ProjectFundListViewAdapter(Context context) {
        this.mContext = context;
    }

    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public Object getItem(int position) {
        return items.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup viewGroup) {
        ViewHolder viewHolder;
        if (convertView == null) {
            ProjectFundListItemBinding binding = DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.project_fund_list_item, viewGroup, false);
            convertView = binding.getRoot();
            viewHolder = new ViewHolder(binding);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        ProjectFundListItemBinding root = viewHolder.getBinding();
        JSONObject item = items.getJSONObject(position);
        root.source.setText(StringUtil.getValue(item.getString("source")));
        root.amount.setText(StringUtil.getValue(item.getString("amount")));
        root.time.setText(StringUtil.getValue(item.getString("time")));
        root.czr.setText(StringUtil.getValue(item.getString("czr")));
        root.czsj.setText(StringUtil.getValue(item.getString("czsj")));

        return convertView;
    }

    public void addItems(JSONArray array) {
        items.addAll(array);
        notifyDataSetChanged();
    }

    public void clear() {
        items.clear();
        notifyDataSetChanged();
    }

    public JSONArray getItems() {
        return items;
    }

    private class ViewHolder {
        private ProjectFundListItemBinding binding;

        public ViewHolder(ProjectFundListItemBinding binding) {
            this.binding = binding;
        }

        public ProjectFundListItemBinding getBinding() {
            return binding;
        }
    }
}
